package com.fyl.oauth2.config;

import com.fyl.oauth2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

/**
 * @Author: 黯然
 * @Date: 2025/4/8 16:14
 * @Description:
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                // permitAll() 的URL路径属于公开访问，不需要权限
                .antMatchers("/public/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/page/**").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/favicon.ico").permitAll()
                .antMatchers("/assets/**/**").permitAll()
                .antMatchers("/index.html").permitAll()

                .antMatchers("/oauth/rest_token*").permitAll()
                .antMatchers("/login*").permitAll()
                .antMatchers("/SingleLogin").permitAll()
                .antMatchers("/signinApp").permitAll()
                .antMatchers("/authentication/require").permitAll()
                .antMatchers("/signout").permitAll()

                // /user/ 开头的URL需要 ADMIN 权限
                .antMatchers("/user/**").hasAnyRole("ADMIN")
                .antMatchers("/role/**").hasAnyRole("ADMIN")
                .antMatchers("/department/**").hasAnyRole("ADMIN")
                .antMatchers("/clientLoginLog/**").hasAnyRole("ADMIN")
                .antMatchers("/client/client_details.do").hasAnyRole("ADMIN")
                .antMatchers("/client/register_client.do").hasAnyRole("ADMIN")
                .antMatchers("/client/update_client.do").hasAnyRole("ADMIN")
                .antMatchers("/client/updateIcon.do").hasAnyRole("ADMIN")
                .antMatchers("/client/archive_client.do").hasAnyRole("ADMIN")
                .antMatchers("/client/test_client.do").hasAnyRole("ADMIN")
                .antMatchers("/client/clientIdList").hasAnyRole("ADMIN")
                .antMatchers("/client/client_details").hasAnyRole("ADMIN")
                .antMatchers("/client/register_client").hasAnyRole("ADMIN")
                .antMatchers("/client/archive_client/**").hasAnyRole("ADMIN")
                .antMatchers("/client/test_client/**").hasAnyRole("ADMIN")


                .antMatchers(HttpMethod.GET, "/login*").anonymous()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/page/views/login/login.html")
                .loginProcessingUrl("/login.do")
                .failureUrl("/login?error=1")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)

                .and()
                // .logout()
                // .logoutUrl("/signout")
                //.deleteCookies("JSESSIONID")
                //.logoutSuccessUrl("/")
                //.and()
                .exceptionHandling();
    }



    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        // 取消账号锁定
        return daoAuthenticationProvider;
    }

    /**
     * BCrypt  加密
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            // 自定义失败逻辑
            request.getSession().setAttribute("error", "登录失败: " + exception.getMessage());
            response.sendRedirect("/login?error");
        };
    }

}
